package com.example.administrator.hqq.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;


import com.example.administrator.hqq.config.LoongsConfig;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @name: HQQ
 * @describe: 相机裁剪功能
 * @author: 康海涛 QQ2541849981
 * @time: 2018/11/1 18:13
 * @remark:
 */

public class CameraUtils {
    private static String TAG = "CameraUtils";
    private static CameraUtils instance;
    private static final String FILE_CONTENT_FILE_PROVIDER = "com.example.administrator.hqq.FileProvider";

    //打开相机
    private static final int REQUEST_CODE_TAKE_PHOTO = 11111;
    //打开相册
    private static final int REQUEST_CODE_SELECT_PICTURE = 11112;
    //剪切图片
    private static final int REQUEST_CODE_CROP_PICTURE = 11113;

    //照片图片名
    private String photo_image;
    //截图图片名
    private String crop_image;
    private String DATE = "";

    private int widthScale = 16;//长宽 比例
    private int heightScale = 9;
    private boolean resetCropSize = false;

    private CameraUtils() {
    }

    public static CameraUtils getInstance() {
        if (instance == null) {
            synchronized (CameraUtils.class) {
                if (instance == null) {
                    instance = new CameraUtils();
                }
            }
        }
        return instance;
    }


    /**
     * 启动相机
     */
    @SuppressLint("SimpleDateFormat")
    public void takeCamera(Activity context) {
        DATE = new SimpleDateFormat("yyyy_MMdd_hhmmss").format(new Date());
        photo_image = createImagePath(DATE);
        File file = new File(photo_image);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {//7.0
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//临时授权
            Uri uri = FileProvider.getUriForFile(context, FILE_CONTENT_FILE_PROVIDER, file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        }
        try {
            context.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
        } catch (ActivityNotFoundException anf) {
            Log.e(TAG, "ActivityNotFoundException: ");
        }
    }

    /**
     * 启动相机Fragment
     */
    public void takeCamera(Fragment fragment) {
        takeCamera(fragment.getActivity());
    }

    /**
     * 调用系统剪裁功能
     */

    public void cropPicture(Activity activity, String path) {
        if (!resetCropSize) {
            widthScale = 16;
            heightScale = 9;
        }
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri;
        Uri outputUri;
        crop_image = createImagePath("crop_" + DATE);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(activity, FILE_CONTENT_FILE_PROVIDER, file);
            outputUri = Uri.fromFile(new File(crop_image));
            //outputUri不需要ContentUri,否则失败
            //outputUri = FileProvider.getUriForFile(activity, "com.solux.furniture.fileprovider", new File(crop_image));
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(new File(crop_image));
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", widthScale);
        intent.putExtra("aspectY", heightScale);
        //设置裁剪图片宽高
//        intent.putExtra("outputX", 526);
//        intent.putExtra("outputY", 246);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
        resetCropSize = false;
    }

    /**
     * 调用系统剪裁功能Fragment
     */
    public void cropPicture(Fragment activity, String path) {
        cropPicture(activity.getActivity(), path);
    }

    /**
     * 调用系统剪裁功能(并设置比例)
     */
    public void cropPicture(Activity activity, String path, int width, int height) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri;
        Uri outputUri;
        crop_image = createImagePath("crop_" + DATE);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(activity, FILE_CONTENT_FILE_PROVIDER, file);
            outputUri = Uri.fromFile(new File(crop_image));
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(new File(crop_image));
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        //设置裁剪图片宽高
        intent.putExtra("outputX", 246 * width);
        intent.putExtra("outputY", 246 * height);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
    }

    /**
     * 调用系统剪裁功能(并设置比例)
     */
    public void cropPicture(Activity activity, String path, int width, int height,boolean isUseBasics,int BasicsSize) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri;
        Uri outputUri;
        crop_image = createImagePath("crop_" + DATE);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(activity, FILE_CONTENT_FILE_PROVIDER, file);
            outputUri = Uri.fromFile(new File(crop_image));
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(new File(crop_image));
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        if (isUseBasics)
        {
            //设置裁剪图片宽高
            intent.putExtra("outputX", 246 * width);
            intent.putExtra("outputY", 246 * height);
        }else{
            intent.putExtra("outputX", BasicsSize * width);
            intent.putExtra("outputY", BasicsSize * height);
        }

        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
    }
    /**
     * 打开系统相册
     */
    @SuppressLint("SimpleDateFormat")
    public void openAlbum(Activity activity) {
        DATE = new SimpleDateFormat("yyyy_MMdd_hhmmss").format(new Date());
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        activity.startActivityForResult(intent, REQUEST_CODE_SELECT_PICTURE);
    }


    public void onActivityResult(Activity activity, int requestCode, int resultCode
            , Intent data, OnResultListener listener) {
        if (resultCode == -1)
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                    if (!TextUtils.isEmpty(photo_image)) {
                        File file = new File(photo_image);
                        if (file.isFile() && listener != null)
                            listener.takePhotoFinish(photo_image);
                    }
                    break;
                case REQUEST_CODE_SELECT_PICTURE:
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            String path = GetPathFromUri.getInstance().getPath(activity, uri);
                            File file = new File(path);
                            if (file.isFile() && listener != null)
                                listener.selectPictureFinish(path);
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_PICTURE:
                    if (!TextUtils.isEmpty(crop_image)) {
                        File file = new File(crop_image);
                        if (file.isFile() && listener != null)
                            listener.cropPictureFinish(crop_image);
                    }
                    break;
            }
        else
            Log.e(TAG, "onActivityResult: resultCode==" + resultCode);
    }

    public void onActivityResult(Fragment activity, int requestCode, int resultCode, Intent data, OnResultListener listener) {
        onActivityResult((Activity) activity.getContext(), requestCode, resultCode, data, listener);
    }

    /**
     * 设置裁剪比例
     *
     * @param widthScale
     * @param heightScale
     */
    public void setCropSize(int widthScale, int heightScale) {
        this.widthScale = widthScale;
        this.heightScale = heightScale;
        resetCropSize = true;

    }

    public interface OnResultListener {
        //拍照回调
        void takePhotoFinish(String path);

        //选择图片回调
        void selectPictureFinish(String path);

        //裁剪回调
        void cropPictureFinish(String path);
    }


    /**
     * 创建图片的存储路径
     */
    private static String createImagePath(String imageName) {
        String dir = LoongsConfig.PICTURE_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(imageName)) {
            file = new File(dir, imageName + ".jpg");
        }
        return file.getAbsolutePath();
    }
}
